package com.gollum.web.security.handler;

import com.alibaba.fastjson2.JSON;
import com.gollum.common.constant.HttpStatus;
import com.gollum.common.domain.response.RestResponse;
import com.gollum.common.utils.ServletUtils;
import com.gollum.common.utils.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * <pre>没有权限异常处理类 </pre>
 *
 * @author Herther
 * @version 1.0.0
 * @createTime 2022年08月23日 22:40:00
 */
@Component
public class UnAuthorizedHandler implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -89701231231277606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(RestResponse.fail(code, msg)));
    }
}
